import {routerRedux} from 'dva/router';
import {message} from 'antd';
import {shopList, userList, userGroup, addBusiness, setBusiness} from '../services/api';

export default {
  namespace: 'businessList',
  state: {
    data: [],
  },

  effects: {
    *fetch({payload}, {call, put}){
      const res = yield call(shopList, payload);
      if (res) {
        yield put({
         type: 'save',
         payload: {data: res}
       });
      }
    },
    *add({ payload }, { call, put }){
      const res = yield call(addBusiness, payload);
      if(res){
        const set = yield call(setBusiness, {
            user_token: res.accessToken,
            action: 1, // 1设置，0取消
        });
        if(set){
             yield put({
              type: 'saveBusiness',
              payload : res.principal
            });
            message.success('新增成功！');
        }
       
      }
    },
    *changeStatus( { payload }, { call, put } ){
        const res = yield call(setBusiness, payload);
        if(res){
            yield put({
                type: 'saveDelBusiness',
                payload:payload
            });
            message.success('成功！');
        }
    },
    *userGroup({ payload }, { call, put }){
      const res = yield call(userGroup, payload);
      if(res){
        yield put({
          type: 'saveGroup',
          payload : payload
        });
        message.success('分组成功！');
      }
    },
    
  },

  reducers: {
    save(state, {payload}){
      return {
        ...state,
        ...payload
      }
    },
    saveBusiness(state, { payload }){
        let data = [...state.data];
        data.push({
            "userId": payload.id,
            "userInfo": payload
        });
        return {
            ...state,
            ...{data: data}
        }  
    },
    saveDelBusiness(state, { payload }){
      let data = [...state.data];
      const { user_id } = payload;
      data = data.filter(v=>{
        return v.userId != user_id
      });
      return {
        ...state,
        ...{data : data}
      }
    },
    saveAddGroup(state, { payload }){
      let group = [...state.group];
      group.push(payload);
      return {
        ...state,
        group
      }
    },
  },
};
